package com.sl.ms.carriage.handler;

import cn.hutool.core.collection.CollUtil;
import com.sl.ms.carriage.domain.dto.WaybillDTO;
import com.sl.ms.carriage.entity.CarriageEntity;
import com.sl.transport.common.exception.SLException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * description:
 *
 * @Author youhongwei
 * @Create 2025/6/23 20:10
 * @Version 1.0
 */
@Component
public class CarriageChainHandlerFactory {

    //注入所有实现 AbsCarriageChainHandler 接口的处理器
    @Resource
    private List<AbsCarriageChainHandler> chainHandlers;

    //责任链的入口处理器
    private AbsCarriageChainHandler firstHandler;

    @PostConstruct
    public void initChain(){
        //检查处理器列表是否为空
        //为空就返回异常
        if(CollUtil.isEmpty(chainHandlers)){
            throw new SLException("not find carriage chain handler");
        }
        //设置责任链的第一个处理器
        firstHandler = chainHandlers.get(0);
        //构建处理器链
        for (int i = 0; i < chainHandlers.size(); i++) {
            if(i == chainHandlers.size() - 1){
                //链尾处理器：下一个设为null(终止链）
                chainHandlers.get(i).setNextHandler(null);
            }else {
                //当前处理器指向下一个处理器
                chainHandlers.get(i).setNextHandler(chainHandlers.get(i+1));
            }
        }
    }

    public CarriageEntity findCarriageEntity(WaybillDTO waybillDTO){
        //从第一个链去执行
        return firstHandler.doHandler(waybillDTO);
    }

}
